import { cline, loc, urlTb } from 'sui';
import { User } from 'cache';

const side_width = 240;

const getClientH = () => document.body.clientHeight;

const getClientW = (side) => {
    const w = document.body.clientWidth
    if (side) {
        return w - side_width - 10;
    }

    return w;
};

const is_empty = (data) => {
    if (!data) {
        return true;
    }

    return data.length <= 0;
};

const cutTxt = (txt, l=4, sub=5) => {
    if (!txt) {
        return "";
    }

    const len = txt.length;
    if (len <= l) {
        return txt;
    }

    let con = txt.substring(0, sub);
    con += "...";

    let pos = len - sub;
    if (pos < sub) {
        pos = sub
    }

    con += txt.substring(pos);

    return con;
};

const obj_empty = (data) => {
    if (!data) {
        return true;
    }

    return Object.keys(data).length <= 0;
};

const obj_str = (v, k) => {
    if (obj_empty(v)) {
        return "";
    }

    const r = v[k];
    if (r) {
        return "" + r;
    }
    else {
        if (`${r}` === "false") {
            return "false";
        }

        if (!isNaN(r)) {
            return "" + r;
        }
    }

    return "";
};

const obj_bool = (v, k) => {
    if (obj_empty(v)) {
        return false;
    }

    const val = v[k];
    if (val === "true") {
        return true;
    }
    else if (val === "false") {
        return false;
    }

    if (val) {
        return val;
    }

    return false;
};

const for_obj = (obj, fn) => {
    if (!obj || !fn) {
        return;
    }

    Object.entries(obj).forEach(([k, v]) => fn(k, v));
};

const obj_int = (v, k) => {
    if (!v) {
        return 0;
    }

    let n = parseInt(v[k], 10);
    if (isNaN(n)) {
        return 0;
    }

    return n;
};

const no_del = (m=loc("l_542")) => {
    if (!window.confirm(m)) {
        return true;
    }

    return false;
};

const obj_date = (v, k) => {
    if (obj_empty(v)) {
        return new Date();
    }

    if (v[k]) {
        return v[k];
    }

    return new Date();
};

const obj_str_trim = (v, k) => {
    let r = obj_str(v, k);
    return r.trim();
};

const get_name = (ksn, kname, data) => {
    let tmp = obj_str(data, ksn);
    let v = obj_str(data, kname);
    if (v) {
        tmp += ` ( ${v} )`;
    }

    return tmp;
};

const cut_text = (v, len=4) => {
    if (!v) {
        return "";
    }

    if (v.length > len) {
        let r = v.slice(0, len);
        r += "...";
        return r;
    }

    return v;
};

const d_sort = (r, k, rev=false) => {
    if (is_empty(r)) {
        return;
    }

    if (rev) {
        r.sort((a, b) => {
            if (a[k] > b[k]) {
                return -1;
            }

            if (a[k] < b[k]) {
                return 1;
            }

            return 0;
        });

        return;
    }

    r.sort((a, b) => {
        if (a[k] > b[k]) {
            return 1;
        }

        if (a[k] < b[k]) {
            return -1;
        }

        return 0;
    });
};

const d_sort_num = (r, k) => {
    if (is_empty(r)) {
        return;
    }

    r.sort((a, b) => parseInt(a[k], 10) - parseInt(b[k], 10));
};

const sn_name = (cur) => {
    const sn = obj_str(cur, "sn");
    const name = obj_str(cur, "name");

    if (name) {
        return `${sn} ( ${name} )`;
    }

    return sn;
};

const to_float = (v) => {
    let n = parseFloat(v);
    if (isNaN(n)) {
        return 0.0;
    }

    return n;
};

const obj_float = (v, k) => {
    if (!v) {
        return 0.0;
    }

    return to_float(v[k]);
};

const trim_data = (v, col) => {
    if (is_empty(v)) {
        return;
    }

    v.forEach(d => {
        col.forEach(k => {
            if (d[k]) {
                d[k] = d[k].trim();
            }
        })
    });
};

const is_obj_eq = (a, b) => {
    if (obj_empty(a) && obj_empty(b)) {
        return true;
    }

    if (obj_empty(a) && !obj_empty(b)) {
        return false;
    }

    if (obj_empty(b) && !obj_empty(a)) {
        return false;
    }

    let eq = true;

    for_obj(a, (k, v) => {
        if (!eq) {
            return;
        }

        if (b[k] === v) {
            return;
        }

        eq = false;
    });

    return eq;
};

const get_umt = (v) => {
    if (v === "T") {
        return loc("l_713");
    } else if (v === "G") {
        return loc("l_712");
    } else if (v === "C") {
        return loc("l_528");
    } else if (v === "S") {
        return loc("l_529");
    }

    return "";
};

const show_yn = (v) => {
    if (v === "Y") {
        return loc("l_820");
    } else if (v === "N") {
        return loc("l_821");
    }

    return v;
};

const show_st = (v) => {
    if (v === "open") {
        return loc("l_301");
    } else if (v === "pause") {
        return loc("l_303");
    } else if (v === "close") {
        return loc("l_302");
    } else if (v === "rej") {
        return loc("l_726");
    } else if (v === "run") {
        return loc("l_300");
    } else if (v === "ok") {
        return loc("l_368");
    } else if (v === "block") {
        return loc("l_304");
    }

    return v;
};

const show_opt = (v) => {
    if (v === "in") {
        return loc("l_117");
    } else if (v === "out") {
        return loc("l_119");
    } else if (v === "pick") {
        return loc("l_741");
    } else if (v === "md") {
        return loc("l_235");
    } else if (v === "pd") {
        return loc("l_154");
    } else if (v === "del") {
        return loc("l_237");
    }

    return v;
};

const show_side = (v) => {
    if (v === "hand") {
        return loc("l_446");
    } else if (v === "auto") {
        return loc("l_756");
    }

    return v;
};

const show_std = (d, sn) => {
    if (!d) {
        return null;
    }

    const tmp = obj_str(d.row, "stdname");
    if (tmp) {
        return tmp
    }

    return obj_str(d.row, sn);
};

const show_tech = (d, sn) => {
    if (!d) {
        return null;
    }

    const tmp = obj_str(d.row, "techname");
    if (tmp) {
        return tmp
    }

    return obj_str(d.row, sn);
};

const show_mt = (tmp, d, w=100) => {
    const sn = obj_str(d, "sn");

    let wd = w;

    let width = obj_str(d, "width");
    if (width) {
        wd = obj_int(d, "width");
    }

    if (sn === "mt") {
        tmp.push({name: d.name, key: sn, width: 100, formatter: props => get_umt(obj_str(props.row, "mt")) });
    } else if (sn === "state") {
        tmp.push({name: d.name, key: sn, width: wd, formatter: props => show_st(obj_str(props.row, sn)) });
    } else if (sn === "yn") {
        tmp.push({name: d.name, key: sn, width: wd, formatter: props => show_yn(obj_str(props.row, sn)) });
    } else if (sn === "side") {
        tmp.push({name: d.name, key: sn, width: wd, formatter: props => show_side(obj_str(props.row, sn)) });
    } else if (sn === "sn" || sn === "insn") {
        tmp.push({name: d.name, key: sn, width: wd, frozen: true});
    } else if (sn === "std") {
        tmp.push({name: d.name, key: sn, width: wd, formatter: props => show_std(props, sn) });
    } else if (sn === "tech") {
        tmp.push({name: d.name, key: sn, width: wd, formatter: props => show_tech(props, sn) });
    } else {
        tmp.push({name: d.name, key: sn, width: wd});
    }
};

const filter_user = (v) => {
    if (is_empty(v)) {
        return null;
    }

    return v.filter(d => d.sn !== "admin");
};

const clear_object = (data) => {
    const ret = [];

    data.forEach(d => {
        const tmp = {};

        for_obj(d, (k, v) => {
            if (typeof v === "object") {
                return;
            }

            tmp[k] = v;
        });

        ret.push(tmp);
    });

    return ret;
};

const adjust = (v) => {
    let tmp = Math.abs(v);
    tmp = Math.floor(tmp * 10) % 10;

    if (tmp <= 5) {
        return Math.trunc(v);
    }
    else {
        return Math.round(v);
    }
};

const stock_log = (tab, psn, wsn, v, k) => {
    const tmp = {
        "uname": User.uName(),
    };

    for_obj(v, (a, b) => tmp[a] = "" + b);

    const val = {
        "psn": psn,
        "wsn": wsn,
        "v": tmp,
    };

    for_obj(k, (a, b) => val["k"][a] = "" + b);

    const cmd = {
        "tab": tab,
        "que": true,
        "line": cline(),
        "data": [val]
    };

    urlTb(null, "chunk", cmd, null, null, false);
};


const save_log = (url=null, ext=null) => {
    if (!ext || !url) {
        return;
    }

    let val = "";

    try {
        const reg = /[\s'"/\\]/g;

        val = JSON.stringify(ext);

        val = val.replaceAll(reg, "");
        val = val.slice(0, 800);
    }
    catch (err) {
        console.log(err);
        val = "";
    }

    if (!val) {
        return;
    }

    urlTb(null, "chunk",
        {
            tab: "syslog",
            que: true,
            line: cline(),
            data: [{
                psn: "",
                wsn: "",
                k: {
                    usn: User.userName(),
                },
                v: {
                    uname: User.uName(),
                    url: url,
                    ext: val,
                }
            }]
        }, null, null, false);
};

export {obj_float, to_float, d_sort, d_sort_num, getClientW, getClientH, no_del, obj_int, obj_empty, for_obj, obj_bool, show_mt, filter_user, show_yn,
    adjust, show_st, clear_object, show_side, show_opt, get_umt, is_obj_eq, trim_data, sn_name, cut_text, obj_str_trim, obj_date, side_width, obj_str,
    save_log, stock_log, get_name, cutTxt, is_empty};
